<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <el-form-item label="名称">
            <el-input v-model="query.name" class="filter-item" placeholder="请输入名称" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button class="" type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button class="" type="primary" @click="add()">添加</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :max-height="height+60" style="width: 100%" row-key="id" lazy :load="listLoad" border @sort-change="sorting">
      <el-table-column prop="name" label="名称" min-width="140" align="left"/>
      <el-table-column prop="area_code" label="行政代码" min-width="160" align="center" sortable="custom"/>
      <el-table-column prop="zip_code" label="邮政编码" min-width="80" align="center" sortable="custom"/>
      <el-table-column prop="city_code" label="区号" min-width="60" align="center" sortable="custom"/>
      <el-table-column prop="level" label="级别" min-width="75" align="center" sortable="custom"/>
      <el-table-column label="操作" min-width="120" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" top="10vh" width="40%" :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formRef" :rules="rules" :model="model" class="" label-width="100px">
        <el-form-item label="父级" prop="parent_code">
          <el-cascader
            v-model="model.parent_code"
            :options="regionTree"
            :props="regionProps"
            clearable
            filterable
            placeholder="一级地区"
            style="width:100%"
            @change="pickParentCode"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="model.name" placeholder="请输入名称：北京市" clearable/>
        </el-form-item>
        <el-form-item label="简称" prop="short_name">
          <el-input v-model="model.short_name" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="model.pinyin" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="行政代码" prop="area_code">
          <el-input v-model="model.area_code" placeholder="请输入编码：110000" clearable/>
        </el-form-item>
        <el-form-item label="邮政编码" prop="zip_code">
          <el-input v-model="model.zip_code" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="区号" prop="city_code">
          <el-input v-model="model.city_code" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="model.lng" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="model.lat" placeholder="" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import {disabledTree} from '@/utils/index'
import {list, info, save, del, tree} from '@/api/admin/region'

export default {
  name: 'AdminRegion',
  components: {Pagination},
  data() {
    return {
      height: 680,
      loading: false,
      datas: [],
      query: {},
      dialogVisible: false,
      dialogTitle: '',
      btnLoading: false,
      model: {
        id: '',
        parent_code: '',
        area_code: '',
        zip_code: '',
        city_code: '',
        name: '',
        short_name: '',
        pinyin: '',
        lng: '',
        lat: '',
        level: '',
        sorting: 100,
        status: ''
      },
      rules: {
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        area_code: [{required: true, message: '请输入行政代码', trigger: 'blur'}]
      },

      regionTree: [],
      regionProps: {
        expandTrigger: 'click',
        checkStrictly: true,
        value: 'area_code',
        label: 'name'
      }
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 树形列表
    tree(row) {
      this.regionTree = []
      tree({}).then(res => {
        if (row) {
          this.regionTree = disabledTree(res.data.data, row.id)
        } else {
          this.regionTree = res.data.data
        }
      }).catch(() => {
      })
    },
    // 添加
    add(row) {
      this.dialogVisible = true
      this.dialogTitle = '新增'
      this.tree()
      if (row) {
        this.model = this.$options.data().model
        this.model.parent_code = row.area_code
      } else {
        this.reset()
      }
    },
    // 修改
    edit(row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑：' + row.id
      this.tree(row)
      info({
        id: row.id
      }).then(res => {
        this.model = res.data
      })
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' + row.id + ' </span> 这条数据吗？',
        'ID：' + row.id,
        {type: 'warning', dangerouslyUseHTMLString: true}
      ).then(() => {
        this.loading = true
        del({
          id: row.id
        }).then(res => {
          this.list()
          this.reset()
          this.$message.success(res.msg)
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    // 提交
    submit() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          this.model.parent_code = this.getParentId(this.model.parent_code)
          save(this.model, 'post').then(res => {
            this.btnLoading = false
            this.list()
            this.reset()
            this.dialogVisible = false
            this.$message.success(res.msg)
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['formRef'] !== undefined) {
        this.$refs['formRef'].resetFields()
      }
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 排序
    sorting(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
        this.list()
      }
    },

    // 懒加载
    listLoad(tree, treeNode, resolve) {
      list({
        parent_code: tree.area_code
      }).then(res => {
        resolve(res.data.data)
      })
    },
    // 父级选择
    pickParentCode(value) {
      if (value) {
        //this.model.parent_id = this.getParentId(value)
      }
    },
    getParentId(ids) {
      if (Array.isArray(ids)) {
        // 取数组最后一项的值
        return ids[ids.length - 1]
      } else {
        return ids
      }
    }
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
